package main

import (
	"fmt"
	"sort"
	"strconv"
)

func main() {

	l1 := strToLink2("5")
	l2 := strToLink2("124")
	result := mergeTwoLists(l1, l2)
	fmt.Println(result)
}

type ListNode struct {
	Val  int
	Next *ListNode
}

func (l *ListNode) String() string {
	lnode := l
	str := ""
	for lnode != nil {
		str += strconv.Itoa(lnode.Val)
		lnode = lnode.Next
	}
	return str
}

func strToLink2(str string) *ListNode {
	root := ListNode{0, nil}
	other := &root // 定义一个指针，指向第一个节点

	for i := 0; i < len(str); i++ {
		v2, _ := strconv.Atoi(string(str[i]))
		tmp := ListNode{v2, nil} // 创建临时节点
		other.Next = &tmp        // 首节点的next 指向临时节点
		other = &tmp             // other 向后移动一格
	}
	return root.Next

}

func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
	result := &ListNode{}
	other := result
	var arr []int

	for l1 != nil || l2 != nil {
		if l2 != nil {
			arr = append(arr, l2.Val)
		}
		if l1 != nil {
			arr = append(arr, l1.Val)
		}

		if l1 != nil {
			l1 = l1.Next
		}
		if l2 != nil {
			l2 = l2.Next
		}
	}

	sort.Ints(arr)

	for _, v := range arr {
		other.Next = &ListNode{v, nil}
		other = other.Next
	}

	return result.Next
}

